<?php
/**
 * Created by XM·Tan.
 * Motto: Who shuts love out, in turn shall be shut out from love.
 * Date: 2021/3/22 18:07
 */

namespace app\admin\middleware;

use app\admin\business\AdminAuth as AdminAuthBus;
use app\admin\business\AdminRole as AdminRoleBus;
use app\common\lib\ArrayLib;
use app\common\lib\Show;
use think\Exception;
use think\facade\Log;
use think\facade\Request;
use think\Response;

class Auth {

    public function handle($request, \Closure $next) {
        // 前置中间件
        if (empty(session(config('admin.session_admin'))) && !preg_match('/login/', $request->pathinfo())) {
            return redirect((string) url('login/index'));
        }

        $admin = session(config('admin.session_admin'));
        if ($admin) {
            $role = (new AdminRoleBus())->getByIds(explode(',',$admin['role_id']));
            $rules = ArrayLib::getPushStringToArray($role);

            $controller = Request::controller(); //获取控制器名
            $action = Request::action(); //获取方法名
            // 根据 控制器名 和方法名 获取对应权限数据
            $row = (new AdminAuthBus())->getByConditionFind(['c' => $controller, 'a' => $action]);
            if ($row) {
                if (!in_array($row['id'], $rules)) {
                    Log::error($admin['username'].' - 抱歉，您没有操作权限!');
                    if (Request::isAjax()) {
                        return Show::error('抱歉，您没有操作权限!', [], 0, 500);
                    } else {
                        throw new Exception('抱歉，您没有操作权限!');
                    }
                }
            }
        }

        // 后置中间件
        $response = $next($request);

        return $response;
        // 后置中间件
    }

    /**
     * 中间件结束调度
     * @param Response $response
     */
    public function end($response) {

    }

}